package com.desgin.pattern.observer.pull;

import lombok.extern.log4j.Log4j2;

import java.util.HashSet;
import java.util.Set;

/**
 * @author SaErNuoSi
 * @date 2018/4/25 8:34
 */
@Log4j2
public class WeatherObservable implements PullSubject {
    /**
     * 标记数据是否改变
     */
    private boolean changed;
    /**
     * 存放观察者的数组
     */
    private Set<PullObserver> observerSet;

    /**
     * 温度
     */
    private float temperature;
    /**
     * 湿度
     */
    private float humidity;
    /**
     * 压力
     */
    private float pressure;

    public WeatherObservable() {
        observerSet = new HashSet<>();
    }

    @Override
    public void registerObserver(PullObserver observer) {
        observerSet.add(observer);
    }

    @Override
    public void removeObserver(PullObserver observer) {
        observerSet.remove(observer);
    }

    @Override
    public void notifyObserver() {
        if (!changed) {
            log.warn("数据状态没有发生改变....");
            return;
        }
        observerSet.stream().forEach(observer -> {
            observer.update(this, null);
        });
    }

    public void weatherChanged() {
        setChanged(true);
        notifyObserver();
    }

    public void setWeatherData(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        weatherChanged();
    }

    public boolean isChanged() {
        return changed;
    }

    public void setChanged(boolean changed) {
        this.changed = changed;
    }

    public float getTemperature() {
        return temperature;
    }

    public float getHumidity() {
        return humidity;
    }

    public float getPressure() {
        return pressure;
    }

    public void setTemperature(float temperature) {
        this.temperature = temperature;
    }

    public void setHumidity(float humidity) {
        this.humidity = humidity;
    }

    public void setPressure(float pressure) {
        this.pressure = pressure;
    }

}
